from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
from we.settings import BASE_DIR
from django.core.paginator import Paginator
from . . import models
from . viewsIndex import uploads
import time,os
from django.db.models import Q



# 商品添加
def goodsadd(request):

    # 获取商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
     
    # 分配数据
    context = {'cateslist':data}
        
    # 加载模板
    return render(request,'myadmin/goods/add.html',context)




# 执行商品添加
def goodsinsert(request):
# try:
    # 接收收据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    data['cateid'] = models.Cates.objects.get(id=data['cateid'])

    # 处理上传的商品主图
    myfite = request.FILES.get('pic_url')
    if myfite:
        data['pic_url'] = uploads(myfite)
    else:
        return HttpResponse("<script>alert('必须上传商品主图');history.back(-1);</script>")

    # 执行数据的添加
    ob = models.Goods(**data)
    ob.save()


    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
# except:        
#     return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_goods_add')+'"</script>')



# 商品列表
def goodsindex(request):
    # 查询
    data = models.Goods.objects.filter().exclude(status=2)

    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types=='all' or types=='title':
            # 多字段的条件搜索
            data = data.filter(Q(title__contains=keywords))
        
        elif types == 'price':
            # 按介个区间搜
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        else:
            # 按指定字段搜索
            search = {types+'__contains':keywords}
            data = data.filter(**search )


    # 实例化分页类  参数1是所有的数据对象,参数2每页显示条数
    paginator = Paginator(data,7)

    # h获取当前页码数 ?p=n
    p =request.GET.get('p',1) 

    # 获取当前页的数据
    userlist = paginator.page(p)

    # 分配数据
    context = {'goodslist':userlist}

    # 添加模板
    return render(request,'myadmin/goods/index.html',context)



# 商品修改
def goodsedit(request,gid):
    # 根据gid获取用户对象
# data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    
    ob = models.Goods.objects.get(id=gid)
    # 判断请求方式
    if request.method == 'GET':
        ab = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        context = {'aginfo':ab,'ginfo':ob}
        # 显示编辑表单
        return render(request,'myadmin/goods/edit.html',context)

    elif request.method == 'POST':
        # 执行编辑
        ob.title = request.POST.get('title')
        # ob.cateid = request.POST.get(id = models.Cates.objects.get(id='cateid'))
        ob.cateid = models.Cates.objects.get(id=request.POST.get('cateid'))
        ob.price = request.POST.get('price')
        ob.store = request.POST.get('store')
        ob.clicknum = request.POST.get('clicknum')
        # 判断是否更新了主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            # 如果修改了主图,要上传新的头像,并判断是否删除以前头像
            if ob.pic_url != '/static/pics/goods.jpg':
                try:
                    # 删除原来上传的主图
                    os.remove(BASE_DIR+ob.pic_url)
                except:
                    pass

            # 更新头像
            ob.pic_url = uploads(myfile)
        # 执行数据的更新
        ob.save()

        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')



# 商品删除
def goodsdel(request,gid):
    try:
        # 根据gid获取用户对象,修改状态
        ob = models.Goods.objects.get(id=gid)
        ob.status = 2
        ob.save()

        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:

        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')
